package avicit.bdp.dds.service.queue;


import avicit.bdp.dds.common.Constants;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * A singleton of a task queue implemented with zookeeper
 * tasks queue implementation
 */
@Service
public class TaskPriorityQueueImpl implements TaskPriorityQueue {
    /**
     * queue size
     */
    private static final Integer QUEUE_MAX_SIZE = 3000;

    /**
     * queue
     */
    private PriorityBlockingQueue<String> queue = new PriorityBlockingQueue<>(QUEUE_MAX_SIZE, new TaskInfoComparator());

    /**
     * put task takePriorityInfo
     *
     * @param taskPriorityInfo takePriorityInfo
     * @throws Exception
     */
    @Override
    public void put(String taskPriorityInfo) throws Exception {
        queue.put(taskPriorityInfo);
    }

    /**
     * take taskInfo
     * @return taskInfo
     * @throws Exception
     */
    @Override
    public String take() throws Exception {
        return queue.take();
    }

    /**
     * queue size
     * @return size
     * @throws Exception
     */
    @Override
    public int size() throws Exception {
        return queue.size();
    }

    /**
     * TaskInfoComparator
     */
    private class TaskInfoComparator implements Comparator<String>{

        /**
         * compare o1 o2
         * @param o1 o1
         * @param o2 o2
         * @return compare result
         */
        @Override
        public int compare(String o1, String o2) {
            String s1 = o1;
            String s2 = o2;
            String[] s1Array = s1.split(Constants.UNDERLINE);
            if(s1Array.length > Constants.TASK_INFO_LENGTH){
                // warning: if this length > 5, need to be changed
                s1 = s1.substring(0, s1.lastIndexOf(Constants.UNDERLINE) );
            }

            String[] s2Array = s2.split(Constants.UNDERLINE);
            if(s2Array.length > Constants.TASK_INFO_LENGTH){
                // warning: if this length > 5, need to be changed
                s2 = s2.substring(0, s2.lastIndexOf(Constants.UNDERLINE) );
            }

            return s1.compareTo(s2);
        }
    }
}
